package com.system.runtai.utils;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.system.runtai.entity.AppletUser;
import com.system.runtai.service.AppletUserService;
import com.system.vo.AppletVO;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Component
public class WXPhoneLogin {
    // AppID
    @Value("${weixin.appid}")
    private String APP_ID;

    // AppSecret
    @Value("${weixin.appSecret}")
    private String APP_SECRET;
    // 微信小程序登录校验请求地址
    private final static String LOGIN_URL = "https://api.weixin.qq.com/sns/jscode2session";



//    @Autowired
//    RestTemplate restTemplate;
//    @Resource
//    private AppletUserService userService;
//    @Bean
//    public RestTemplate restTemplate() {
//        return new RestTemplate();
//    }
//    获取手机号
//    public String login(AppletUser loginUser){
//
////        需要一个叫acesstoken的参数
//        Accesstoken getaccesstoken = this.getaccesstoken();
//
//        String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token="+getaccesstoken.getAccess_token()+"&code=" + loginUser.getPhonecode();
//
//        Map<String, Object> requestParam = new HashMap<String, Object>();
//        requestParam.put("code", loginUser.getPhonecode());
////        requestParam.put("access_token",accesstoken.getAccess_token());
//        ResponseEntity<JSONObject> wxResult = restTemplate.postForEntity(url, requestParam, JSONObject.class);
//
//        JSONObject phoneInfo = wxResult.getBody().getJSONObject("phone_info");
//
//// 通过键名获取phoneNumber的值
//        String phoneNumber = phoneInfo.getString("phoneNumber");
//        System.out.println(phoneNumber);
//        User user = new User();
//        user.setUphone(phoneNumber);
//        return  phoneNumber;
////        try {
//////            user.setUname(loginUser.getUname());
//////            user.setUprofile(loginUser.getUprofile());
////            if(user!=null){   //拿到手机号
////                User userbyUphone = userService.getUserbyUphone(user.getPhone());
////                Map<String, Object> cliams = new HashMap<>();
////                cliams.put("phone",user.getPhone());
////                String token = JwtUtils.generateJwt(cliams);
////                Map<String, Object> user1 = new HashMap<>();
////                user1.put("token",token);
////                user1.put("phone",user.getPhone());
//////                手机号一定存在，因为前面已经用openid验证了
//////                if(userbyUphone == null){
//////                    Integer integer = userService.addUser(user);
////                    return user1;
//////                }else {
//////                    return new ResultInfo(200,"登录成功",user1);
//////                }
////            }else {  //没有拿到手机号
////                return null;
////            }
////        } catch (Exception e) {
////            throw new RuntimeException(e);
////        }
//    }
//
//
//    public Accesstoken getaccesstoken(){
//        Accesstoken accesstoken = null ;
//        String accessurl="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+APP_ID+"&secret="+APP_SECRET;
//        HttpClient client = HttpClients.createDefault(); // 创建默认http连接
//        HttpGet getRequest = new HttpGet(accessurl);// 创建一个post请求
////        LoginDTO loginDTO = new LoginDTO(); // 存储下面http请求返回的结果
//        try {
//            // 用http连接去执行get请求并且获得http响应
//            HttpResponse response = client.execute(getRequest);
//            // 从response中取到响实体
//            HttpEntity entity = (HttpEntity) response.getEntity();
//            // 把响应实体转成文本
//            String html = EntityUtils.toString((HttpEntity) entity);
//             accesstoken = JSON.parseObject(html, Accesstoken.class);
//            System.out.println("输出");
//            System.out.println(accesstoken.toString());
//        }catch (IOException e) {
//            e.printStackTrace();
////      return ResponseDTO.errorByMsg(CodeMsg.USER_WX_LOGIN_ERROR);
//        }
//        return accesstoken;
//
//    }





    /**
     * 小程序获取openid
     */
    public  LoginDto appWxLogin(String code) {
        String url = LOGIN_URL + "?appid=" + APP_ID + "&secret="+ APP_SECRET + "&grant_type=authorization_code&js_code=" +code ;
        System.out.println(url);
        HttpClient client = org.apache.http.impl.client.HttpClients.createDefault(); // 创建默认http连接
        HttpGet getRequest = new HttpGet(url);// 创建一个post请求
        LoginDto loginDto =null;
//        LoginDTO loginDTO = new LoginDTO(); // 存储下面http请求返回的结果
        try {
            // 用http连接去执行get请求并且获得http响应
            HttpResponse response = client.execute(getRequest);
            // 从response中取到响实体
            HttpEntity entity = response.getEntity();


            // 把响应实体转成文本
            String html = EntityUtils.toString(entity);

            loginDto = JSON.parseObject(html, LoginDto.class);
            System.out.println("输出");
            System.out.println(loginDto.toString());

        } catch (IOException e) {
            e.printStackTrace();

        }

        return loginDto;
    }





    }
